package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;



import cn.edu.sdjzu.xg23.kcsj01_backend.entity.EmployeeAssPatent;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.Patent;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.SupportingMaterial;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.AbsAchievementMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.EmployeeAssPatentMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.PatentMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.FileService;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.PatentService;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.SupportingMaterialService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.SnowflakeIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PatentServiceImpl implements PatentService {
    @Autowired
    private PatentMapper patentMapper;
    @Autowired
    private AbsAchievementMapper absAchievementMapper;
    @Autowired
    private SnowflakeIdGenerator idGenerator;
    @Autowired
    private EmployeeAssPatentMapper employeeAssPatentMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private SupportingMaterialService supportingMaterialService;

    private static final Logger log = LoggerFactory.getLogger(SupportMaterialServiceImpl.class);

    @Override
    @Transactional // 声明事务
    public boolean addPatent(Patent patent) {
        Long sharedId = idGenerator.generateId();

        // 1. 插入 Achievement 相关记录
        absAchievementMapper.addAchievement(sharedId, "专利");

        // 2. 插入 Patent 记录
        patent.setId(sharedId);
        boolean success = patentMapper.addPatent(patent);
        boolean insertSuccess = false;
        boolean insertFilesSuccess = false;
        if (success && patent.getApplicants() != null && !patent.getApplicants().isEmpty()) {
            for (EmployeeAssPatent applicant : patent.getApplicants()) {
                applicant.setPatent(new Patent(sharedId));// 设置专利关联
            }

             insertSuccess  = employeeAssPatentMapper.insertApplicants(patent.getApplicants());
        }

        if (insertSuccess && patent.getSupportingMaterials() != null && !patent.getSupportingMaterials().isEmpty()) {
            for (SupportingMaterial supportingMaterial : patent.getSupportingMaterials()) {
                supportingMaterial.setAchievement(new Patent(sharedId));// 添加Achievement关联
            }
           insertFilesSuccess  = supportingMaterialService.addSupportingMaterials(sharedId, patent.getSupportingMaterials());
        }


        return success && insertSuccess &&  insertFilesSuccess ;
    }

    @Override
    @Transactional
    public boolean deletePatent(Long patentId) {
        try {
            // 1. 删除关联的支撑材料文件（仅处理物理文件）
            boolean materialsDeleted = supportingMaterialService.deleteSupportingMaterials(patentId);
            if (!materialsDeleted) {
                log.error("删除专利关联的支撑材料文件失败，专利ID: {}", patentId);
                return false;
            }

            // 2. 删除专利记录（数据库自动级联删除支撑材料记录）
            return absAchievementMapper.deleteById(patentId);
        } catch (Exception e) {
            log.error("删除专利失败，专利ID: {}", patentId, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updatePatent(Patent patent) {
        // 1. 更新专利基本信息
        boolean updateSuccess = patentMapper.updatePatent(patent);

        if (updateSuccess) {
            Long patentId = patent.getId();

            // 2. 处理申报人信息
            if (patent.getApplicants() != null) {
                employeeAssPatentMapper.deleteByPatentId(patentId);
                for (EmployeeAssPatent applicant : patent.getApplicants()) {
                    applicant.setPatent(new Patent(patentId));
                }
                boolean applicantSuccess = employeeAssPatentMapper.insertApplicants(patent.getApplicants());
                if (!applicantSuccess) {
                    return false;
                }
            }

            // 3. 委托支撑材料服务处理支撑材料更新
            if (patent.getSupportingMaterials() != null) {
                boolean materialsUpdated = supportingMaterialService.updateSupportingMaterials(
                        patentId, patent.getSupportingMaterials()
                );
                if (!materialsUpdated) {
                    return false;
                }
            }
        }

        return updateSuccess;
    }



    @Override
    public PageInfo<Patent> selectPatentsByCondition(Integer pageNum, Integer pageSize, Patent patent,Long employeeId) {
        PageHelper.startPage(pageNum, pageSize);
        List<Patent> patentList = patentMapper.selectPatentsByCondition(patent,employeeId);
        return new PageInfo<>(patentList);
    }



    @Override
    public boolean transformPatent(Patent patent) {
        return patentMapper.transformPatent(patent);
    }

    @Override
    public boolean approvePatent(Patent patent) {
        return patentMapper.approvePatent(patent);
    }
}
